#pragma once

#include <vector>
#include <queue>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "Thread.hpp"

using namespace std;
using namespace ThreadModule;

const static int gdefaultnum = 10;

template <class T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }

    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadWakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    ThreadPool(int threadnum = gdefaultnum) : _threadnum(threadnum), _waitnum(0), _run(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        LOG(INFO, "ThreadPool create!");
    }

    void HandlerTask(string name)
    {
        LOG(INFO, "%s is running...", name.c_str());
        while (true)
        {
            LockQueue();
            while (_taskq.empty() && _run)
            {
                _waitnum++;
                ThreadSleep();
                _waitnum--;
            }
            if (_taskq.empty() && !_run)
            {
                UnlockQueue();
                break;
            }
            T t = _taskq.front();
            _taskq.pop();
            UnlockQueue();
            LOG(DEBUG, "%s get task", name.c_str());
            t();
            LOG(DEBUG, "%s hander task,result:%s", name.c_str(), t.ResToStr().c_str());
        }
    }

    void InitThreadPool()
    {
        for (int num = 0; num < gdefaultnum; num++)
        {
            string name = "thread-" + to_string(num + 1);
            auto handler = bind(&ThreadPool::HandlerTask, this, placeholders::_1);
            _threads.emplace_back(handler, name);
            LOG(INFO, "init %s done", name.c_str());
        }
        _run = true;
    }

    void Start()
    {
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }

    ThreadPool<T> &operator=(const ThreadPool<T> &) = delete; // 复制拷贝禁用
    ThreadPool(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetInstance()
    {
        if (_instance == nullptr)
        {
            LockGuard lockguard(&_lock);
            if (_instance == nullptr)
            {
                _instance = new ThreadPool<T>();
                _instance->InitThreadPool();
                _instance->Start();
                LOG(DEBUG, "create single instance threadpool");
                return _instance;
            }
        }
        LOG(DEBUG, "get single instance threadpool");
        return _instance;
    }

    void Stop()
    {
        LockQueue();
        _run = false;
        ThreadWakeupAll();
        UnlockQueue();
    }

    void Wait()
    {
        for (auto &thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quit...", thread.name().c_str());
        }
    }

    bool Enqueue(const T &t)
    {
        bool ret = false;
        LockQueue();
        if (_run)
        {
            _taskq.push(t);
            if (_waitnum > 0)
            {
                ThreadWakeup();
            }
            LOG(DEBUG, "enqueue task success");
            ret = true;
        }
        UnlockQueue();
        return ret;
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadnum;
    vector<Thread> _threads;
    queue<T> _taskq;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
    int _waitnum;
    bool _run;

    static ThreadPool<T> *_instance;
    static pthread_mutex_t _lock;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;